import { NextRequest, NextResponse } from 'next/server';
import { getDbInstance } from '@/lib/sqlite-database';
import fs from 'fs';
import path from 'path';

export async function POST(request: NextRequest) {
  try {
    // 读取CSV文件
    const csvFilePath = path.join(process.cwd(), 'excel/06-21/计量单位定义表.csv');
    if (!fs.existsSync(csvFilePath)) {
      return NextResponse.json({ success: false, error: '计量单位定义表.csv 文件不存在' }, { status: 400 });
    }
    const csvContent = fs.readFileSync(csvFilePath, 'utf-8');
    const lines = csvContent.split('\n').map(line => line.trim()).filter(line => line.length > 0);

    // 跳过前两行（表名和表头）
    const dataLines = lines.slice(2);
    const validPairs = new Set();
    const measurementUnits: Array<{ category: string; unit: string }> = [];

    for (const line of dataLines) {
      // 以逗号分割，最多8列
      const cols = line.split(',').map(col => col.trim());
      for (let i = 0; i < 8; i += 2) {
        const category = cols[i] || '';
        const unit = cols[i + 1] || '';
        // 跳过无效、空、"—"、"单计量位"等
        if (!category || !unit || category === '—' || unit === '—' || unit === '单计量位') continue;
        // 去重
        const key = `${category}__${unit}`;
        if (!validPairs.has(key)) {
          validPairs.add(key);
          measurementUnits.push({ category, unit });
        }
      }
    }

    // 清空原有数据
    const sqliteDb = getDbInstance();
    sqliteDb.clearMeasurementUnits();
    // 批量插入
    for (const mu of measurementUnits) {
      sqliteDb.insertMeasurementUnit(mu);
    }

    return NextResponse.json({
      success: true,
      count: measurementUnits.length,
      units: measurementUnits
    });
  } catch (error) {
    return NextResponse.json({ success: false, error: error instanceof Error ? error.message : String(error) }, { status: 500 });
  }
}

export async function GET() {
  try {
    const sqliteDb = getDbInstance();
    const units = await sqliteDb.getAllMeasurementUnits();
    return NextResponse.json({
      success: true,
      data: units,
      count: units.length
    });
  } catch (error) {
    console.error('获取计量单位数据失败:', error);
    return NextResponse.json({
      success: false,
      error: '获取计量单位数据失败: ' + (error as Error).message
    }, { status: 500 });
  }
} 